// src/components/Notebook.vue
<template>

  <div>
    <h2>记事本</h2>
    <div class="container notebook">
    <div style="display: block;clear: both;" class="line64">
      <div class="left-inline-block line64">
        <!-- 触发创建记事弹窗的按钮 -->
        <button @click="showAddNoteModal = true">添加记事</button>
      </div>      
    </div>
    
    <!-- 创建记事弹窗 -->
    <div v-if="showAddNoteModal" class="modal" @click.self="closeAddNoteModal">
        <div class="modal-content" @click.stop>
            <form @submit.prevent="addNote" class="note-body">
                <h2>添加记事</h2>
                <div class="form-group">
                    <label for="new-title" class="form-label">标题:</label>
                    <input v-model="newNote.title" id="new-title" class="form-input" required />
                </div>
                <div class="form-group">
                    <label for="new-content" class="form-label">内容:</label>
                    <textarea v-model="newNote.content" id="new-content" class="form-textarea" required></textarea>
                </div>
                <div class="form-actions" style="text-align: right; padding-right: 50px; margin-top: 20px;">
                    <button @click="closeAddNoteModal" class="white-button">取消</button>
                    <button type="submit" class="ml8">添加</button>
                </div>
            </form>
        </div>
    </div>
    <div class="note-list">
      <div v-for="(note) in paginatedNotes" :key="note.id" class="note-item">
        <div class="note-content">
            <p>
                <h2>{{ note.title }}</h2>
            </p>          
            <p class="" style="text-align: right; height: 48px;line-height: 48px;">
                <span style="display: inline; float: left;">{{ formatDate(note.updatedAt) }}</span>
                <button @click="viewNote(note.id)">查看</button>
                <button @click="editNote(note.id)" class="orange-button ml8">编辑</button>
                <button @click="deleteNote(note.id)"  class="red-button ml8">删除</button>
            </p>          
        </div>
      </div>
    </div>
    <div class="pagination" v-if="paginatedNotes.length > 0">
      <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
      <span>第 {{ currentPage }} 页</span>
      <button @click="nextPage" :disabled="currentPage === totalPages">下一页</button>
    </div>
    <div v-if="editingNoteId !== null" class="edit-note">
        <div class="close-icon" @click="closeEditDialog">&times;</div>
      <h2>编辑记事</h2>
      <form @submit.prevent="updateNote">
        <div>
          <label for="edit-title">标题:</label>
          <input v-model="editingNote.title" id="edit-title" required />
        </div>
        <div>
          <label for="edit-content">内容:</label>
          <textarea v-model="editingNote.content" id="edit-content" required></textarea>
        </div>
        <button type="submit">保存</button>
      </form>
    </div>

     <!-- 查看记事详情的模态框或区域 -->
     <div v-if="viewingNoteId !== null" class="modal">
        <div class="modal-content note-body">
            <div>
                <h3>{{ viewingNote.title }}</h3>
                <span>最后更新: {{ formatDate(viewingNote.updatedAt) }}</span>
            </div>
            <div>
                <p>{{ viewingNote.content }}</p>              
            </div>
            <div style="text-align: right; margin-right: 8px;">
                <button @click="closeViewNote" >关闭</button>
            </div>
        </div>
    </div>
  </div>
  </div>

</template>

<script lang="ts">
import { defineComponent, ref, onMounted, computed } from 'vue';
import { openDB } from 'idb';

interface Note {
  id: number;
  title: string;
  content: string;
  updatedAt?: number;
}

export default defineComponent({
  name: 'Notebook',
  setup() {
    const newNote = ref<Partial<Note>>({ title: '', content: '' , updatedAt: 0});
    const notes = ref<Note[]>([]);
    const editingNoteId = ref<number | null>(null);
    const editingNote = ref<Partial<Note>>({ title: '', content: '' });
    const currentPage = ref(1);
    const notesPerPage = 10;

    const showAddNoteModal = ref(false);

    const dbPromise = openDB('notebook-db', 1, {
      upgrade(db) {
        if (!db.objectStoreNames.contains('notes')) {
          db.createObjectStore('notes', { keyPath: 'id', autoIncrement: true });
        }
      },
    });

    // 新增查看记事的状态和响应式数据
    const viewingNoteId = ref<number | null>(null);
    const viewingNote = ref<Partial<Note>>({ title: '', content: '', updatedAt: 0 });
 
    // 查看记事的处理函数
    const viewNoteHandler = async (id: number) => {
      const db = await dbPromise;
      const tx = db.transaction('notes', 'readonly');
      const store = tx.objectStore('notes');
      const request = store.get(id);
      const result = await request;
      if (result && result.updatedAt !== undefined) {
        viewingNoteId.value = id;
        viewingNote.value = { ...result };
      }
    };

    const fetchNotes = async () => {
      const db = await dbPromise;
      const tx = db.transaction('notes', 'readonly');
      const store = tx.objectStore('notes');
      const result = await store.getAll();
      notes.value = (result as Note[]).sort((a, b) =>(b.updatedAt as number)- (a.updatedAt as number));
    };

    const paginatedNotes = computed(() => {
      const start = (currentPage.value - 1) * notesPerPage;
      const end = start + notesPerPage;
      return notes.value.slice(start, end);
    });

    const totalPages = computed(() => Math.ceil(notes.value.length / notesPerPage));

    const prevPage = () => {
      if (currentPage.value > 1) currentPage.value--;
    };

    const nextPage = () => {
      if (currentPage.value < totalPages.value) currentPage.value++;
    };

    const formatDate = (timestamp: number | undefined) => {
      if(timestamp === undefined){
        return '';
      }

      const date = new Date(timestamp);
      return `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`;
    };

    const addNoteHandler = async () => {
      if (!newNote.value.title || !newNote.value.content) return;
      const db = await dbPromise;
      const tx = db.transaction('notes', 'readwrite');
      const store = tx.objectStore('notes');
    //   const newNoteWithId: Note = 
      await store.add({
        ...newNote.value,
        updatedAt: Date.now(),
      });
      newNote.value = { title: '', content: '' };
      await fetchNotes();
      closeAddNoteModal();
    };

    const closeAddNoteModal = () => {
      showAddNoteModal.value = false;
      // 清除表单数据（可选）
      newNote.value = { title: '', content: '' };
      // ...
    }

    const editNoteHandler = async (id: number) => {
      const db = await dbPromise;
      const tx = db.transaction('notes', 'readonly');
      const store = tx.objectStore('notes');
      const request = store.get(id);
      const result = await request;
      if (result) {
        editingNoteId.value = id;
        editingNote.value = { ...result };
      }
    };

    const deleteNoteHandler = async (id: number) => {
      const db = await dbPromise;
      const tx = db.transaction('notes', 'readwrite');
      const store = tx.objectStore('notes');
      await store.delete(id);
      await fetchNotes();
    };

    const updateNoteHandler = async () => {
      if (!editingNote.value.title || !editingNote.value.content) return;
      const db = await dbPromise;
      const tx = db.transaction('notes', 'readwrite');
      const store = tx.objectStore('notes');
      await store.put({
        ...editingNote.value,
        updatedAt: Date.now(),
      });
      closeEditDialog();
      await fetchNotes();
    };

    const closeEditDialog = () => {
        editingNoteId.value = null;
        editingNote.value = { title: '', content: '' };
    };

    onMounted(fetchNotes);
        // 关闭查看记事的处理函数
        const closeViewNote = () => {
      viewingNoteId.value = null;
      // 可选：清空viewingNote以避免内存泄漏（虽然Vue会自动处理）
      viewingNote.value = { title: '', content: '', updatedAt: 0 };
    };

    return {
      newNote,
      notes,
      editingNoteId,
      editingNote,
      currentPage,
      paginatedNotes,
      totalPages,
      viewingNoteId,
      viewingNote,
      showAddNoteModal,
      prevPage,
      nextPage,
      formatDate,
      addNote: addNoteHandler,
      editNote: editNoteHandler,
      deleteNote: deleteNoteHandler,
      updateNote: updateNoteHandler,
      viewNote: viewNoteHandler,
      closeViewNote,
      closeAddNoteModal,
      closeEditDialog,      
    };
  },
});
</script>

<style lang="scss" scoped>
@use "../assets/common.scss";
@use "../assets/button.scss";
@use "../assets/notebook.scss";
</style>